#####################################################################
#                                                                   #
#  THIS IS A SOURCE CODE FILE FROM A PROGRAM TO INTERACT WITH THE   #
# LBRY PROTOCOL ( lbry.com ). IT WILL USE THE LBRY SDK ( lbrynet )  #
# FROM THEIR REPOSITORY ( https://github.com/lbryio/lbry-sdk )      #
# WHICH I GONNA PRESENT TO YOU AS A BINARY. SINCE I DID NOT DEVELOP #
# IT AND I'M LAZY TO INTEGRATE IN A MORE SMART WAY. THE SOURCE CODE #
# OF THE SDK IS AVAILABLE IN THE REPOSITORY MENTIONED ABOVE.        #
#                                                                   #
#      ALL THE CODE IN THIS REPOSITORY INCLUDING THIS FILE IS       #
# (C) J.Y.Amihud and Other Contributors 2021. EXCEPT THE LBRY SDK.  #
# YOU CAN USE THIS FILE AND ANY OTHER FILE IN THIS REPOSITORY UNDER #
# THE TERMS OF GNU GENERAL PUBLIC LICENSE VERSION 3 OR ANY LATER    #
# VERSION. TO FIND THE FULL TEXT OF THE LICENSE GO TO THE GNU.ORG   #
# WEBSITE AT ( https://www.gnu.org/licenses/gpl-3.0.html ).         #
#                                                                   #
# THE LBRY SDK IS UNFORTUNATELY UNDER THE MIT LICENSE. IF YOU ARE   #
# NOT INTENDING TO USE MY CODE AND JUST THE SDK. YOU CAN FIND IT ON #
# THEIR OFFICIAL REPOSITORY ABOVE. THEIR LICENSE CHOICE DOES NOT    #
# SPREAD ONTO THIS PROJECT. DON'T GET A FALSE ASSUMPTION THAT SINCE #
# THEY USE A PUSH-OVER LICENSE, I GONNA DO THE SAME. I'M NOT.       #
#                                                                   #
# THE LICENSE CHOSEN FOR THIS PROJECT WILL PROTECT THE 4 ESSENTIAL  #
# FREEDOMS OF THE USER FURTHER, BY NOT ALLOWING ANY WHO TO CHANGE   #
# THE LICENSE AT WILL. SO NO PROPRIETARY SOFTWARE DEVELOPER COULD   #
# TAKE THIS CODE AND MAKE THEIR USER-SUBJUGATING SOFTWARE FROM IT.  #
#                                                                   #
#####################################################################

# This file with handle various analytics. Currently in LBRY Desktop
# or Odysee.com, the analytics are very basic, while they have a very
# rich SDK that allows to get all kinds of information about transactions.
# This transaction data is useful to get various Analytics.

from subprocess import *
import json
import time

from flbry import url
from flbry import settings
from flbry import markdown
from flbry import channel
from flbry.variables import *

def graph(data=[]):

    # This function will draw a graph. I wanted originally to make it a
    # part of variables.py, but I'm afraid it will be a huge function.
    # And it makes a lot of sense to put it here (in Analytics).

    # Concept art:

    # 2021-11-15  --------------------------------------> 2021-12-30
    #
    #           #
    #           #
    #           #         #           #                 #            #
    #           #       ###    #      ##  #       #     #      #     #
    #  #       ##      ######  #     ####### #   ##    ###    ##   # #
    #  #  #    ### ########### ### # #########  ###   #####  ###  ####
    # #################################################### ###########
    # ################################################################

    if not data:
        center("No Data!", "bdrd")
        return
    if len(data) == 1:
        center("Only one entry! Cannot draw graph!", "bdrd")
        return
    
    w, h = tsize()

    height = h - 5
    width = w - 16

    times = []
    values = []
    
    for i in data:
        times.append(i["timestamp"])
        try:
            values.append(float(i["amount"]))
        except:
            values.append(0)

    #for i in times:
    #    print(i)
    # Finding times
    import time
    startdate = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime( min(times)) )
    enddate  =  time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime( max(times)))

    center(startdate+" "+("-"*(width-(len(startdate)+len(enddate))-6))+"> "+enddate)
    
    ctimes = []
    for i in times:
        ctimes.append(i-min(times))

        
    # LET'S START DRAWING

    
    p = []
    for i in ctimes:
        pix = round((width-1)/max(ctimes)*i)
        p.append(pix)

    ap = []
    for i in range(width):
        count = 0
        for n, d in enumerate(p):
            if d == i:
                count = count + values[n]
        ap.append(count)

    choice = " ░▒▓█"
    if settings.get("graph_force_ASCII"):
        choice = " .~8#"
    
    for i in reversed(range(height)):
        
        va = max(ap) * ((i+1)/(height-1))
        
        s = clr["bdma"]+" "+wdth(va, 5)+" "
         

        for b in ap:
            x = ((height-1)/max(ap)*b)
            
            c = max(min(round((x - i)*4), 4), 0)

            y = choice[c]
            s = s +  clr["bdbu"]+clr["tdcy"]+y


        print("    "+s+clr["bdma"]+" "+clr["norm"])

    center(" ")
    
        
def sales(mode="sales"):

    # This function will show sales of non-gratis publications.


    # First let's get the list of our channels
    out = check_output([lbrynet_binary["b"],
                         "channel", "list"])

    try:
        out = json.loads(out)
    except:
        center("Connect to LBRY first.")
        return
    channels = []
    for i in out["items"]:
        channels.append(i["claim_id"])

    page = 1
    cached = 0 # Page that was loaded last
        
    while True:

        w, h = tsize()
        
        page_size =  h - 5
        
        
        command = [lbrynet_binary["b"],
                   "claim", "search",
                   "--remove_duplicates",
                    '--order_by=release_time',
                   '--page='+str(page),
                   '--page_size='+str(page_size)]
        if mode == "sales":
            command.append('--fee_amount=>0')
            
        for i in channels:
            command.append("--channel_ids="+i)

        if page != cached:
            list_of_publications = check_output(command)
            try:
                list_of_publications = json.loads(list_of_publications)
            except:
                center("Connect to LBRY first.")
                return
            
            if mode == "sales":
                data_print = {"categories":["Publication", "Price", "Sold Copies"],
                          "size":[5,1,1],
                          "data":[]}
            else:
                data_print = {"categories":["Publication", "Supported Times"],
                          "size":[5,2],
                          "data":[]}
            print()
            for n, i in enumerate(list_of_publications["items"]):



                name = i["name"]
                try:
                    name = i["value"]["title"]
                except:
                    pass
                #print( name )

                price = 0
                try:
                    price = i["value"]["fee"]["amount"]
                except:
                    pass
                #print(price)

                progress_bar(n+1, len(list_of_publications["items"]), "Fetching: "+name)

                # Now lets get the amount of entries in txo
                command = [lbrynet_binary["b"],
                                "txo", "list",
                                "--claim_id="+i["claim_id"],
                                "--page_size=1"]
                if mode == "sales":
                    command.append("--type=purchase")
                txo = check_output(command)
                try:
                    txo = json.loads(txo)
                except:
                    center("Connect to LBRY first.")
                    return

                sold = 0
                try:
                    sold = txo["total_items"]
                except:
                    pass
                #print(sold)
                if mode == "sales":
                    data_print["data"].append([name, price, sold])
                else:
                    data_print["data"].append([name, sold])

            print()
        table(data_print)
        cached = page
        center("---type 'more' to load more---")

        # Now the 'more' and such.

        c = input(typing_dots())
        if not c:
            break

        # TODO: Please test that this even works.
        if c == "more":
            page = page + 1
            
        else:
            try:
                c = int(c)
                total = data_print["data"][c][-1]
                i = list_of_publications["items"][c]
                cpage = 1
                items = []
                while total > 0:
                    command = [lbrynet_binary["b"],
                                    "txo", "list",
                                    "--claim_id="+i["claim_id"],
                               "--page_size=50",
                               "--page="+str(cpage)]
                    if mode == "sales":
                        command.append("--type=purchase")
                    txo = check_output(command)
                    try:
                        txo = json.loads(txo)
                    except:
                        center("Connect to LBRY first.")
                        return
                    cpage = cpage + 1
                    for i in txo["items"]:
                        items.append(i)
                    total = total - 50
                
                graph(items)
                input()
                print()
            
            except:
                pass

        
